<!--
 * @Author       : xh
 * @Date         : 2022-10-19 17:05:57
 * @LastEditors  : xh
 * @FileName     :
-->
<template>
  <div>
    <!-- 省市区选择封装 -->
    <div v-if="type === 1">
      <el-select
        v-model="val"
        :disabled="disabled"
        :placeholder="placeholder"
        filterable
        :multiple="multiple"
        clearable
        :style="customerStyle"
        @change="changeSelectCity"
      >
        <el-option v-for="item in options" :key="item.code" :label="item.name" :value="item.code" />
      </el-select>
    </div>
    <div v-else>
      <el-cascader
        v-model="val"
        :disabled="disabled"
        :options="options"
        :placeholder="placeholder"
        :props="cprop"
        clearable
        :style="customerStyle"
        @change="changeSelectCity"
      />
    </div>
  </div>
</template>
<script>
export default {
  name: 'UCity'
}
</script>
<script setup>
// const citysList = require('province-city-china/dist/level.json')
import cityList from '@/utils/level'
const only = ['82', '81', '50', '31', '12', '11']
import { defineProps, onMounted, ref, defineEmits, defineExpose } from 'vue'

const props = defineProps({
  // 级联级别  1 省   2 市  3 县
  type: {
    default: 1,
    type: Number
  },
  // 是否可搜索
  filterable: {
    type: Boolean,
    default: false
  },

  // 是否多选
  multiple: {
    type: Boolean,
    default: false
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // value: {
  //   type: [String, Number, Array],
  //   default: ''
  // },
  // 占位符
  placeholder: {
    type: String,
    default: '请选择'
  },

  // 自定义样式
  customerStyle: {
    type: Object,
    default() {
      return {}
    }
  }
})

// console.log('citysList', props)
const emits = defineEmits(['change'])

const val = ref(props.type ? '' : [])
const citysList = ref(cityList)
const options = ref([])
const cprop = ref({
  value: 'code',
  label: 'name',
  children: 'children',
  multiple: props.multiple
})

onMounted(() => {
  getSelectOption()
})

// @xh专属注释
// @name:直接设置 默认值   溯级处理
// @params: treeLevel true-需要溯级   false  直接赋值
// @des:
const setValue = (v, treeLevel = false) => {
  if (props.multiple && (typeof v === 'string' || typeof v === 'number')) {
    console.error('多选状态下 ,默认值必须为数组')
    return
  }
  if (!treeLevel) {
    if (props.multiple) {
      // debugger
      let arr = []
      switch (props.type) {
        case 1:
          val.value = v
          // debugger
          break
        case 2:
          arr = v.map((it) => {
            return code2area(it[it.length - 1])
          })
          val.value = arr
          break
        case 3:
          arr = v.map((it) => {
            return code2area(it[it.length - 1])
          })
          val.value = arr
          break
        default:
          break
      }
    } else {
      val.value = v
      // debugger
    }
  } else {
    let arr
    // 自动构造数据
    switch (props.type) {
      case 1:
        // 省级
        val.value = v
        break
      case 2:
        // 省级 市级
        arr = v.map((it) => {
          return this.code2area(it)
        })
        if (props.multiple) {
          val.value = arr
        } else {
          val.value = arr[0]
        }
        break
      case 3:
        // 省级 市级 县级
        arr = v.map((it) => {
          return code2area(it)
        })
        if (props.multiple) {
          val.value = arr
        } else {
          val.value = arr[0]
        }
        break
      default:
        break
    }
  }
}

// 地域编码 转为三位地域数组地区多选用到
const arr2area = (arr) => {
  if (!arr[0]) {
    return
  }
  const str = arr[0]
  let a = str.slice(0, 2)
  let b = str.slice(2, 4)
  let c = str.slice(4, 6)
  c = `${a}${b}${c}`
  b = `${a}${b}00`
  a = `${a}0000`
  return [a, b, c].slice(0, props.type)
}

const code2area = (str) => {
  let a = str.slice(0, 2)
  let b = str.slice(2, 4)
  let c = str.slice(4, 6)
  const spec = only.includes(a)
  c = `${a}${b}${c}`
  b = `${a}${b}00`
  a = `${a}0000`
  if (spec) {
    // 特殊省份
    return [a, c].slice(0, props.type)
  } else {
    return [a, b, c].slice(0, props.type)
  }
}

// @xh专属注释
// @name:
// @params:
// @des:重置
const resetVale = () => {
  if (props.type === 1) {
    val.value = ''
  } else {
    val.value = []
  }
}

// 结果返回
const changeSelectCity = (val) => {
  let res = {
    data: val,
    result: null
  }
  if (cprop.value.multiple) {
    switch (cprop.value.type) {
      case 1:
        // 省级
        res = {
          data: val,
          result: val
        }
        break
      case 2:
        // 省级 市级
        res = {
          data: val,
          result: val.map((it) => {
            return it[1]
          })
        }
        break
      case 3:
        // 省级 市级 县级
        res = {
          data: val,
          result: val.map((it) => {
            return it[it.length - 1]
          })
        }
        break
      default:
        break
    }
  } else {
    if (cprop.value.type == 1) {
      res = {
        data: val,
        result: val
      }
    } else {
      res = {
        data: val,
        result: val[val.length - 1]
      }
    }
  }
  emits('change', res)
  // debugger
}

// @xh专属注释
// @name:
// @params:
// @des:初始化选型
const getSelectOption = () => {
  // 如果是1 只拿省的数据
  if (props.type === 1) {
    getProvinceList()
  } else if (props.type === 2) {
    getcitysList()
  } else {
    options.value = citysList.value
  }
}

// 获取省分下拉
const getProvinceList = () => {
  const res = []
  citysList.value.forEach((item) => {
    const obj = {}
    obj.code = item.code
    obj.name = item.name
    res.push(obj)
  })
  options.value = res
}
// 获取省市数据
const getcitysList = () => {
  const res = []
  citysList.value.forEach((item) => {
    const obj = {
      code: '',
      name: '',
      children: []
    }
    obj.code = item.code
    obj.name = item.name
    item.children.forEach((val) => {
      const or = {}
      or.code = val.code
      or.name = val.name
      obj.children.push(or)
    })
    res.push(obj)
  })
  options.value = res
}

defineExpose({ setValue, resetVale })
</script>

<style scoped lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  /* vertical-align: -0.15em; */
  vertical-align: 0;
  fill: currentColor;
  overflow: hidden;
  margin-right: 0;
}
</style>
